package com.ceo.common.utils;

import com.ceo.common.http.exception.PlatformException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author uto_dev_008
 * @desc
 * @since 2023/6/2 9:34
 * Copyright (c)  All rights reserved
 */
@Component
public class CommonContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CommonContextUtil.applicationContext = applicationContext;
    }


    public static <T> T getBean(Class<T> c) {
        try {
            T cc = applicationContext.getBean(c);
            return cc;
        } catch (Exception e) {
            throw new PlatformException(e.getMessage(), 10000001);
        }
    }


    public static <T> T getBeanByName(String name) {
        try {
            T cc = (T) applicationContext.getBean(name);
            return cc;
        } catch (Exception e) {
            throw new PlatformException(e.getMessage(), 10000001);
        }
    }

    public static ApplicationContext getApplicationContext() {

        return applicationContext;

    }
    public static <T> List<T> getBeanListOfType(Class<T> clazz) {
        List<T> result = new ArrayList<>();
        Map<String, T> map = applicationContext.getBeansOfType(clazz);
        if (null != map) {
            result.addAll(map.values());
        }
        return result;
    }

}
